% This function merges the multi-dimension histogram to a specified
% marginal dimensions.
function MarginQW=DistApp_Hist_MergeQW2Marginal(UnitNumList,TargetDimList,QW,FormatFlag)

%% Preliminaries
% Check Dimension Consistency
QW_Full     =   full(QW);
if prod(UnitNumList)~=length(QW_Full)
    error('Dimension is inconsistent!');
end
if nargin<4
    FormatFlag  =   'Vector';
end
% Support Space Dimensions
N_Dim       =   length(UnitNumList);
% Vectorized Quadrature Grid Weights into Matrix Form
QW_Mat      =   reshape(QW_Full,UnitNumList(:)');
% The dimensions which will be aggregated over.
SumDimList  =   sort(setdiff((1:1:N_Dim)',TargetDimList));
MarginQW_Mat=   sum(QW_Mat,SumDimList);
switch FormatFlag
    case 'Vector'
        MarginQW    =   MarginQW_Mat(:);
    case 'Matrix'
        MarginQW    =   squeeze(MarginQW_Mat);
end
